package com.ctgu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctgu.common.ResponseResult;
import com.ctgu.model.dto.LoginDto;
import com.ctgu.model.entity.LoginUser;
import com.ctgu.model.entity.SystemLog;
import com.ctgu.service.IRoleService;
import com.ctgu.service.LoginService;
import com.ctgu.service.SystemLogService;
import com.ctgu.utils.JwtUtil;
import com.ctgu.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private SystemLogService systemLogService;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //AuthenticationManager,authenticationManager 进行认证
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginDto.getUserName(),loginDto.getPassword());
        //会通过UserDetailsService方法进行效验
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登入失败");
        }
        //如果认证通过，使用userid通过jwt生成相对于token
        LoginUser loginUser=(LoginUser) authenticate.getPrincipal();
        String roleName=roleService.getById(loginUser.getUser().getRoleId()).getName();
        String id= String.valueOf(loginUser.getUser().getId());
        String jwt= JwtUtil.createJWT(roleName+":"+id);
        //把用户信息存入Redis中，key为id
        Map<String,String> map=new HashMap<>();
        map.put("token",jwt);
        map.put("data", String.valueOf(loginUser));
        redisCache.setCacheObject("login:"+roleName+":"+id,loginUser,8, TimeUnit.HOURS);
        LambdaQueryWrapper<SystemLog> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SystemLog::getDate);
        List<SystemLog> list = systemLogService.list(wrapper);
        SystemLog one=(SystemLog) list.get(0);
        one.setVisits(one.getVisits()+1);
        systemLogService.updateById(one);
        return new ResponseResult(200,"登入成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("系统异常，用户未登录");
        }
        String roleName=roleService.getById(loginUser.getUser().getRoleId()).getName();
        String redisKey="login:"+roleName+":"+loginUser.getUser().getId().toString();
        redisCache.deleteObject(redisKey);
        return new ResponseResult(200,"退出成功");
    }
}
